/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package person.schedule;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "person_schedule")
@ViewScoped
public class Main extends Beans {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    private Find person_scheduleFind = new Find();
    private List<Beans> person_scheduleList = new ArrayList<>();
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();
    public String filtrofecha;

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
        map.clear();
        logged.setMap(map);
    }

    private void load() {
        try {
            map.clear();
            map.put("ph.id = " + logged.getDetailId(), " ");

            person_scheduleList.clear();
            person_scheduleList = person_scheduleFind.byMap(map);

            setId_persona(person_scheduleList.get(0).getId_persona());
            setPeriodoinicial(person_scheduleList.get(0).getPeriodoinicial());
            setPeriodofinal(person_scheduleList.get(0).getPeriodofinal());
            setIdl_dia(person_scheduleList.get(0).getIdl_dia());
            setHoraentrada(person_scheduleList.get(0).getHoraentrada());
            setHorasalida(person_scheduleList.get(0).getHorasalida());
            setId_persona_asignatura(person_scheduleList.get(0).getId_persona_asignatura());
            setId_sede(person_scheduleList.get(0).getId_sede());
            setAula(person_scheduleList.get(0).getAula());
            getDocente_asignatureBeans().setNombre(person_scheduleList.get(0).getDocente_asignatureBeans().getNombre());
            getUniversityBeans().setId(person_scheduleList.get(0).getUniversityBeans().getId());
            getUniversity_locationBeans().setNombre(person_scheduleList.get(0).getUniversityBeans().getNombre());

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            if (getUniversityBeans().getId() == 0) {
                throw new Exc("m24");
            }
            if (getId_sede() == 0) {
                throw new Exc("m23");
            }
            if (getId_persona_asignatura() == 0) {
                throw new Exc("m22");
            }


            map.clear();
            map.put("ph.id_persona = " + logged.getMasterId(), " AND ");
            map.put("periodoinicial = '" + getPeriodoinicial(), "' AND ");
            map.put("periodofinal = '" + getPeriodofinal(), "' AND ");
            map.put("idl_dia = " + getIdl_dia(), " AND ");
            map.put("horaentrada = '" + getHoraentrada(), "' AND ");
            map.put("horasalida = '" + getHorasalida(), "' AND ");
            map.put("id_persona_asignatura = " + getId_persona_asignatura(), " AND ");
            map.put("id_sede = " + getId_sede(), " AND ");
            map.put("aula = '" + getAula(), "' ");
            if (person_scheduleFind.byExist(map)) {
                throw new Exc("m5");
            }

            String fecha = sdf.format(getPeriodoinicial());
            String fecha1 = sdf.format(getPeriodofinal());
            String hora_entrada = getHoraentrada();
            String hora_salida = getHorasalida();
            map.clear();
            map.put(" ph.id_persona = " + String.valueOf(logged.getMasterId()), " AND ");
            map.put("idl_dia = " + getIdl_dia(), " AND ");
            map.put("id_sede <> " + getId_sede(), " AND ");
            map.put("( periodoinicial  BETWEEN '" + fecha + "'", " and ' " + fecha1 + "' OR ");
            map.put("periodofinal  BETWEEN '" + fecha + "'", " and ' " + fecha1 + "') AND ");
            map.put("horaentrada >= '" + hora_salida + "' AND minutes ('" + hora_salida + "',", "ph.horaentrada ) <= 60 ");

            if (person_scheduleFind.byExist(map)) {
                throw new Exc("m25");
            }

            map.clear();
            map.put(" ph.id_persona = " + String.valueOf(logged.getMasterId()), " AND ");
            map.put("idl_dia = " + getIdl_dia(), " AND ");
            map.put("id_sede <> " + getId_sede(), " AND ");
            map.put("( periodoinicial  BETWEEN '" + fecha + "'", " and ' " + fecha1 + "' OR ");
            map.put("periodofinal  BETWEEN '" + fecha + "'", " and ' " + fecha1 + "') AND ");
            map.put("horasalida <= '" + hora_entrada + "' AND minutes ( horasalida", ",'" + hora_entrada + "' ) <= 60 ");

            if (person_scheduleFind.byExist(map)) {
                throw new Exc("m25");
            }

            sql = "INSERT INTO public.persona_horario (id_persona, periodoinicial, periodofinal, idl_dia , horaentrada , horasalida , id_persona_asignatura , id_sede , aula ) "
                    + "VALUES (" + logged.getMasterId()
                    + ",'" + getPeriodoinicial() + "', "
                    + "'" + getPeriodofinal() + "', "
                    + getIdl_dia() + ", "
                    + "'" + getHoraentrada() + "', "
                    + "'" + getHorasalida() + "', "
                    + getId_persona_asignatura() + ", "
                    + getId_sede() + ", "
                    + "'" + getAula() + "')";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);
            map.clear();
            map.put("ph.id_persona = " + logged.getMasterId(), " AND ");
            map.put("periodoinicial = '" + getPeriodoinicial(), "' AND ");
            map.put("periodofinal = '" + getPeriodofinal(), "' AND ");
            map.put("idl_dia = " + getIdl_dia(), " AND ");
            map.put("horaentrada = '" + getHoraentrada(), "' AND ");
            map.put("horasalida = '" + getHorasalida(), "' AND ");
            map.put("id_persona_asignatura = " + getId_persona_asignatura(), " AND ");
            map.put("id_sede = " + getId_sede(), " AND ");
            map.put("aula = '" + getAula(), "' ");
            person_scheduleList = person_scheduleFind.byMap(map);
            logged.setDetailId(person_scheduleList.get(0).getId());
            clearBeans();
            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {

            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }
            map.clear();
            map.put("ph.id <> " + logged.getDetailId(), " AND ");
            map.put("ph.id_persona = " + logged.getMasterId(), " AND ");
            map.put("periodoinicial = '" + getPeriodoinicial(), "' AND ");
            map.put("periodofinal = '" + getPeriodofinal(), "' AND ");
            map.put("idl_dia = " + getIdl_dia(), " AND ");
            map.put("horaentrada = '" + getHoraentrada(), "' AND ");
            map.put("horasalida = '" + getHorasalida(), "' AND ");
            map.put("id_persona_asignatura = " + getId_persona_asignatura(), " AND ");
            map.put("id_sede = " + getId_sede(), " AND ");
            map.put("aula = '" + getAula(), "' ");


            if (person_scheduleFind.byExist(map)) {
                throw new Exc("m5");
            }
            if (getId_persona_asignatura() == 0) {
                throw new Exc("m22");
            }
            if (getId_sede() == 0) {
                throw new Exc("m23");
            }

            String fecha = sdf.format(getPeriodoinicial());
            String fecha1 = sdf.format(getPeriodofinal());
            String hora_entrada = getHoraentrada();
            String hora_salida = getHorasalida();
            map.clear();
            map.put(" ph.id_persona = " + String.valueOf(logged.getMasterId()), " AND ");
            map.put("idl_dia = " + getIdl_dia(), " AND ");
            map.put("id_sede <> " + getId_sede(), " AND ");
            map.put("( periodoinicial  BETWEEN '" + fecha + "'", " and ' " + fecha1 + "' OR ");
            map.put("periodofinal  BETWEEN '" + fecha + "'", " and ' " + fecha1 + "') AND ");
            map.put("horaentrada >= '" + hora_salida + "' AND minutes ('" + hora_salida + "',", "ph.horaentrada ) <= 60  AND ");
            map.put("horasalida >= '" + hora_entrada + "' AND minutes ( horasalida", ",'" + hora_entrada + "' ) <= 60 ");
            if (person_scheduleFind.byExist(map)) {
                throw new Exc("m25");
            }
            map.put(" ph.id_persona = " + String.valueOf(logged.getMasterId()), " AND ");
            map.put("( periodoinicial  BETWEEN '" + fecha + "'", " and ' " + fecha1 + "' OR ");
            map.put("periodofinal  BETWEEN '" + fecha + "'", " and ' " + fecha1 + "') AND ");
            map.put("horaentrada >= '" + hora_salida + "' AND minutes ('" + hora_salida + "',", "ph.horaentrada ) <= 60  AND ");
            map.put("horasalida >= '" + hora_entrada + "' AND minutes ( horasalida", ",'" + hora_entrada + "' ) <= 60 ");
            if (person_scheduleFind.byExist(map)) {
                throw new Exc("m25");
            }
            sql = "UPDATE public.persona_horario SET "
                    + "id_persona = " + logged.getMasterId() + ", "
                    + "periodoinicial = '" + getPeriodoinicial() + "', "
                    + "periodofinal = '" + getPeriodofinal() + "', "
                    + "idl_dia = '" + getIdl_dia() + "', "
                    + "horaentrada = '" + getHoraentrada() + "', "
                    + "horasalida = '" + getHorasalida() + "', "
                    + "id_persona_asignatura = '" + getId_persona_asignatura() + "', "
                    + "id_sede = '" + getId_sede() + "', "
                    + "aula = '" + getAula() + "' "
                    + "WHERE id = " + logged.getDetailId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);
            clearBeans();
            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }

    }

    public void delete() {
        try {
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id
            deleteById(logged.getDetailId());

            logged.setDetailId(0);
            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }

    }

    public void deleteById(int id) throws Exc, SQLException, Exception {

        //Verifica si el usuario ya existe para otra persona
        sql = "DELETE FROM public.persona_horario "
                + "WHERE id = " + id;

        persistencia.executeUpdate(sql);
        clear();
    }

    public void clear() throws ParseException {
        logged.setDetailId(0);
        clearBeans();
    }

    public void find() throws Exc, SQLException, Exception {
        String fecha_inicial = sdf.format(getPeriodoinicial());
        String fecha_final = sdf.format(getPeriodofinal());
        map.clear();
        map.put("ph.id_persona = " + String.valueOf(logged.getMasterId()), " AND ");
        if (fecha_inicial != null) {
            map.put("periodoinicial  BETWEEN '" + fecha_inicial + "'", " and ' " + fecha_final + "  '" + " OR ");
            map.put("periodofinal  BETWEEN '" + fecha_inicial + "'", " and ' " + fecha_final + "  '");
        }
        logged.setMap(map);

    }

    public void selectedRecordId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    public void selectedAsignatura(ValueChangeEvent event) {
        getDocente_asignatureBeans().setId(Integer.parseInt(event.getNewValue().toString()));
    }

    public void selectedUniversity(ValueChangeEvent event) {
        getUniversityBeans().setId(Integer.parseInt(event.getNewValue().toString()));
    }

    public void selectedUniversity_based(ValueChangeEvent event) {
        getUniversity_locationBeans().setId(Integer.parseInt(event.getNewValue().toString()));
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }

    public void displayMessage(String message) {
        msg.showMsg(namePackage(), "system", message);
    }
}
